#读取A股所有股票当前的交易信息，包括
import baostock as bs
import pandas as pd
from datetime import datetime, timedelta

# 登录系统
lg = bs.login()
print('login respond error_code:' + lg.error_code)
print('login respond  error_msg:' + lg.error_msg)

# 获取昨天的日期
yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")

# 获取所有股票的基本信息
rs = bs.query_stock_basic()
data_list = []
while (rs.error_code == '0') & rs.next():
    data_list.append(rs.get_row_data())

# 将股票信息存储在DataFrame中
stock_df = pd.DataFrame(data_list, columns=rs.fields)

# 过滤出A股股票（过滤掉基金类品种）
# 根据type字段过滤，1代表股票
a_stock_df = stock_df[stock_df['type'] == '1']
#B_stock_df = stock_df[stock_df.type == '1'] 另一种表示方法，供参考
# 获取每只A股的交易数据，并逐条输出
for index, row in a_stock_df.iterrows():
    stock_code = row['code']
    stock_name = row['code_name']  # 获取股票名称
    print(f"股票名称: {stock_name}, 股票代码: {stock_code}")
    
    # 查询单只股票的交易数据
    rs = bs.query_history_k_data_plus(
        stock_code,
        "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
        start_date=yesterday, end_date=yesterday, frequency="d", adjustflag="3")
    
    while (rs.error_code == '0') & rs.next():
        data = rs.get_row_data()
        print(data)  # 输出单只股票的交易数据
    print("-" * 50)  # 输出分隔线
    


# 登出系统
bs.logout()